import {
    SUCC_CODE,
    TIMEOUT,
    HOME_RECOMMEND_PAGE_SIZE,
    jsonpOpitons
} from "./config";
import jsonp from "../assets/js/jsonp";
const axios = require("axios");

//随机打乱数组顺序
const shuffle = arr => {
    const arrLength = arr.length;
    let i = arrLength;
    let rndNum;

    while (i--) {
        if (i !== (rndNum = Math.floor(Math.random() * arrLength))) {
            [arr[i], arr[rndNum]] = [arr[rndNum], arr[i]];
        }
    }

    return arr;
};

export const getHomeSlider = () => {
    return axios
        .get("https://www.imooc.com/api/home/slider", {
            timeout: TIMEOUT
        })
        .then(res => {
            // console.log(res);
            if (res.data.code === SUCC_CODE) {
                //随机获取一张幻灯片
                let sliders = res.data.slider;
                const slider = [sliders[Math.floor(Math.random() * sliders.length)]];
                sliders = shuffle(sliders.filter(() => Math.random() >= 0.5));
                if (sliders.length === 0) {
                    sliders = slider;
                }
                // return res.data.slider;
                return sliders;
            }
            throw new Error("获取数据失败");
        })
        .catch(err => {
            if (err) {
                console.log(err);
            }
            return [{
                linkUrl: "#",
                picUrl: require("../assets/img/404.png")
            }];
        })

};

//获取热门的推荐数据
export const getHomeRecommend = (
    page = 1,
    psize = HOME_RECOMMEND_PAGE_SIZE
) => {
    const url = "https://ju.taobao.com/json/tg/ajaxGetItemsV2.json";
    const params = {
        page,
        psize,
        type: 0,
        frontCatId: ""
    };
    return jsonp(url, params, jsonpOpitons)
        .then(res => {
            if (res.code === "200") {
                console.log(res);
                return res;
            }
            throw new Error("获取数据失败");
        })
        .catch(err => {
            if (err) {
                console.log(err);
            }
        })
};